package com.ruoyi.common.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class WechatMiniProgramQRCode {

    // 替换为你的小程序信息
    private static final String APPID = "wxddcfd0103320c8f4";
    private static final String SECRET = "5c1c5b9caba05da705774092c6eeef95";
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    private static final String QR_CODE_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s";



    // 获取Access Token
    public static String getAccessToken() throws IOException {


        String url = String.format(ACCESS_TOKEN_URL, APPID, SECRET);
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("GET");
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        // 解析JSON响应，提取access_token
        // 示例响应：{"access_token":"xxxx","expires_in":7200}
        String json = response.toString();
        if (json.contains("access_token")) {
            return json.split("\"")[3]; // 简单提取，实际建议用JSON库解析
        }
        return null;
    }

    // 生成小程序码并保存为图片
    public static void generateQRCode2(String accessToken, String scene, String page, int width,String savePath,String orderNo) throws IOException {
        String url = String.format(QR_CODE_URL, accessToken);
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/json");

        // 构建请求参数
        String jsonParams = String.format(
                "{\"scene\":\"%s\",\"page\":\"%s\",\"width\":%d,\"is_hyaline\":true}",
                scene, page, width
        );

        // 发送请求
        OutputStream os = conn.getOutputStream();
        os.write(jsonParams.getBytes());
        os.flush();


        // 处理响应（图片二进制流）
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            try (InputStream is = conn.getInputStream();
                 FileOutputStream fos = new FileOutputStream(savePath)) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                System.out.println("小程序码已保存至：" + savePath);
            }
        } else {
            // 错误处理
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
    }


    public static byte[] generateQRCode(String accessToken, String scene, String page, int width) throws IOException {
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        String env="release";//正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
        try {
            conn = (HttpURLConnection) new URL(String.format(QR_CODE_URL, accessToken)).openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/json");

            // 发送请求参数
            OutputStream os = conn.getOutputStream();
            os.write(String.format("{\"scene\":\"%s\",\"page\":\"%s\",\"env_version\":\"%s\",\"width\":%d}", scene, page,env, width).getBytes());
            os.flush();

            // 处理响应
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = conn.getInputStream();
                outputStream = new ByteArrayOutputStream();

                // 传统流复制方式（兼容 Java 8）
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }

                return outputStream.toByteArray();
            } else {
                // 读取错误流
                inputStream = conn.getErrorStream();
                outputStream = new ByteArrayOutputStream();

                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }

                throw new IOException("生成二维码失败: " + new String(outputStream.toByteArray()));
            }
        } finally {
            // 确保关闭所有流
            if (inputStream != null) inputStream.close();
            if (outputStream != null) outputStream.close();
            if (conn != null) conn.disconnect();
        }
    }

    // 在图片上添加订单号
    public static void addOrderNumberToImage(byte[] qrCodeBytes, String orderNumber, String savePath) throws IOException {
        // 读取原始二维码图片
        BufferedImage qrImage = ImageIO.read(new ByteArrayInputStream(qrCodeBytes));

        // 计算新画布大小（原图高度 + 50像素文字区域）
        int newHeight = qrImage.getHeight() + 50;
        BufferedImage combinedImage = new BufferedImage(qrImage.getWidth(), newHeight, BufferedImage.TYPE_INT_RGB);

        // 获取绘图对象
        Graphics2D g = combinedImage.createGraphics();
        g.setBackground(Color.WHITE);
        g.clearRect(0, 0, qrImage.getWidth(), newHeight);

        // 绘制原始二维码
        g.drawImage(qrImage, 0, 0, null);

        // 设置文字样式
        g.setColor(Color.BLACK);
        g.setFont(new Font("微软雅黑", Font.BOLD, 20));
        FontMetrics metrics = g.getFontMetrics();

        // 计算文字居中位置
        int textWidth = metrics.stringWidth(orderNumber);
        int x = (qrImage.getWidth() - textWidth) / 2;
        int y = qrImage.getHeight() + 35; // 文字底部距离二维码下方30px

        // 绘制文字
        g.drawString(orderNumber, x, y);
        g.dispose();

        // 保存图片
        File output = new File(savePath);
        if (!output.getParentFile().exists()) {
            output.getParentFile().mkdirs();
        }
        ImageIO.write(combinedImage, "png", output);
    }


}